package game

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
)

type ModMail struct {
	MailMap map[int64]*Mail

	player *Player
	path   string
}

func (self *ModMail) HandleGetOffLineMail() {
	OffLineMail := GetMailEngine().GetUserMail(self.player.UserId)
	if OffLineMail != nil {
		for _, v := range OffLineMail {
			self.MailMap[v.MailID] = v
		}
	}
}

func (self *ModMail) HandleSendMailToMailEngine() {
	for {
		fmt.Println("请输入需要发送的玩家id")
		var userid int64
		fmt.Scan(&userid)
		fmt.Println("请输入需要发送的邮件标题")
		var mailtitle string
		fmt.Scan(&mailtitle)
		fmt.Println("请输入需要发送的邮件内容")
		var mailtext string
		fmt.Scan(&mailtext)

		lvMail := new(Mail)
		lvMail.ReceiveId = userid
		lvMail.MailTitle = mailtitle
		lvMail.MailText = mailtext
		lvMail.MailID = GetMailEngine().AddCurMailID()

		GetMailEngine().SendMailToChannel(lvMail)

		fmt.Println("默认此功能为离线邮件，请再按1上线拉取离线邮件数据")

		return
	}
}

func (self *ModMail) HandleDeleteMail() {
	fmt.Println("该功能暂时未开放")
}

func (self *ModMail) HandleDeleteAllMail() {
	if self.MailMap != nil {
		for k := range self.MailMap {
			delete(self.MailMap, k)
		}
	}
	fmt.Println("已删除所有邮件")
}

func (self *ModMail) HandleShowAllMail() {
	fmt.Println("当前邮件如下")
	if self.MailMap != nil {
		for _, v := range self.MailMap {
			fmt.Println(fmt.Sprintf("当前邮件id：%d", v.MailID))
			fmt.Println(fmt.Sprintf("当前邮件标题：%s", v.MailTitle))
			fmt.Println(fmt.Sprintf("当前邮件内容：%s", v.MailText))
		}
	}
}

func (self *ModMail) LoadData(player *Player) {

	self.player = player
	self.path = self.player.localPath + "/Mail.json"

	configFile, err := ioutil.ReadFile(self.path)
	if err != nil {
		self.InitData()
		return
	}
	err = json.Unmarshal(configFile, &self)
	if err != nil {
		self.InitData()
		return
	}

	return
}

func (self *ModMail) SaveData() {
	content, err := json.Marshal(self)
	if err != nil {
		return
	}
	err = ioutil.WriteFile(self.path, content, os.ModePerm)
	if err != nil {
		return
	}
}

func (self *ModMail) InitData() {
	if self.MailMap==nil{
		self.MailMap=make(map[int64]*Mail,0)
	}
}